<?php

class DSlideshow extends CFormModel {

    private $_fileName = 'slideshow.json';
    public $params;
    
    public $id, $title, $link, $file, $thumb, $activated_flag, $preview_flag;

    public function init() {
        $this->params = Yii::app()->params['slideshow'];
        if ($this->getScenario() ==  'insert') {
            $this->activated_flag = true;
        }
    }
    
    public function getAttribute($name) {
        return $this->$name;
    }
    
    private function getAttributesEx() {
        return array(
            'title'          => $this->title,
            'link'           => $this->link,
            'file'           => $this->file,
            'thumb'          => $this->thumb,
            'activated_flag' => (boolean) $this->activated_flag,
            'preview_flag'   => (boolean) $this->preview_flag,
        );
    }
    
    public function attributeLabels() {
        return array(
            'order'          => 'Stt',
            'info'           => 'Thông tin',
            'title'          => 'Tiêu đề',
            'link'           => 'Liên kết',
            'preview_flag'   => 'Xem trước',
            'activated_flag' => 'Hiện',
            'file'           => 'Ảnh',
            'sort'           => 'Sắp xếp',
            'status'         => 'Trạng thái',
        );
    }
    
    public function rules() {
        return array(
            array('title', 'required'),
            array('thumb', 'required',
                'message' => Yii::t('DadminModule.msg', 'required_file', array(
                    '{0}' => $this->getAttributeLabel('file'),
                ))
            ),
            array('activated_flag, preview_flag', 'boolean'),
            array('link, file, id', 'safe'),
        );
    }

    protected function makeFile($aVar) {
        $filePath = Yii::app()->params['components_dir'] . $this->_fileName;
        return file_put_contents($filePath, $aVar);
    }

    /**
     * Get content for json file
     * @return array
     */
    public function getContent() {
        $filePath = Yii::app()->params['components_dir'] . $this->_fileName;
        
        if (! is_file($filePath)) {
            $this->makeFile('');
        }

        $content = file_get_contents($filePath);
        return json_decode($content, true);
    }
    
    /**
     * Write content to file
     * @return string
     */
    public function setContent($content) {
        if (is_array($content))
            $content = json_encode ($content);
        
        $filePath = Yii::app()->params['components_dir'] . $this->_fileName;
        return file_put_contents($filePath, $content);
    }

    /**
     * Make a column active or inactive
     * @param string $cols
     * @param integer $id
     */
    public function toggleColumn($cols, $id) {
        $content = $this->getContent();
        $result = false;
        
        foreach ($content as $key => $item) {
            if (isset($content[$key]) && ($key == $id)) {
                $content[$key][$cols] = ! ($content[$key][$cols]);
                $result = true;
            }
        }
        
        if ($result) $this->setContent($content);
        return $result;
    }
    
    /**
     * Control sort order
     * @param string $direct the direction, such as: first, last, down
     * @param integer $id
     */
    public function sortOrder($direct, $id) {
        $content = $this->getContent();
        $newContent = '';
        
        switch ($direct) {
            case 'first' : {
                $newContent = $this->sortMakeFirst($content, $id);
            } break;
            case 'last' : {
                $newContent = $this->sortMakeLast($content, $id);
            } break;
            case 'down' : {
                $newContent = $this->sortMakeDown($content, $id);
            }
        }
        
        if ($newContent) {
            $this->setContent($newContent);
            return TRUE;
        } else {
            return FALSE;
        }
    }
    
    /**
     * Move record to Top
     * @param array $content
     * @param integer $id
     * @return array
     */
    private function sortMakeFirst($content, $id) {
        $result = '';

        if (isset($content[$id])) {
            $result['1'] = $content[$id];
            $maxRepeat = count($content);

            for ($i = 1; $i <= $maxRepeat; $i++) {
                if ($i < $id) { // re-index
                    $result[$i + 1] = $content[$i];
                } elseif ($i > $id) {
                    $result[$i] = $content[$i];
                }
            }
        }

        return $result;
    }
    
    /**
     * Move record to Last
     * @param array $content
     * @param integer $id
     * @return array
     */
    private function sortMakeLast($content, $id) {
        $result = '';

        if (isset($content[$id])) {
            $maxRepeat = count($content);
            $aTemp = $content[$id];

            for ($i = 1; $i <= $maxRepeat; $i++) {
                if ($i < $id) { // re-index
                    $result[$i] = $content[$i];
                } elseif ($i > $id) {
                    $result[$i - 1] = $content[$i];
                }
            }
            
            $result[$maxRepeat] = $aTemp;
        }

        return $result;
    }
    
    /**
     * Move record to down
     * @param array $content
     * @param integer $id
     * @return array
     */
    private function sortMakeDown($content, $id) {
        $result = '';

        if (isset($content[$id])) {
            $maxRepeat = count($content);
            
            if ($id != $maxRepeat) {
                //swap
                $aTemp = $content[$id];
                $nextId = (int)($id) + 1;
                $content[$id] = $content[$nextId];
                $content[$nextId] = $aTemp;

                $result = $content;
            }
        }

        return $result;
    }
    
    /**
     * Delete record
     * @param integer $id
     * @return boolean
     */
    public function delete($id) {
        $content = $this->getContent();

        if (isset($content[$id])) {
            $newContent = $this->sortMakeLast($content, $id);
            $maxRepeat = count($newContent);
            
            //delete file
            $dir = Yii::app()->params['upload_dir']
                . $this->params['basename'] . '/';
            
            $filePath = $dir . $newContent[$maxRepeat]['file'];
            if (is_file($filePath)) unlink($filePath);
            
            $filePath = $dir . $newContent[$maxRepeat]['thumb'];
            if (is_file($filePath)) unlink($filePath);
            
            unset($newContent[$maxRepeat]);
            $this->setContent($newContent);
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function save() {
        $this->beforeSave();
        $content = $this->getContent();
        
        if (empty($this->id)) { //create
            $maxRepeat = count($content) + 1;
            $this->id = $maxRepeat;
            $content[$maxRepeat] = $this->getAttributesEx();
            
            $content = $this->sortMakeFirst($content, $maxRepeat);
        } else { //update
            $content[$this->id] = $this->getAttributesEx();
        }
        
        $this->setContent($content);
        $this->afterSave();
        
        return true;
    }
    
    protected function beforeSave() {
        if ($this->getScenario() == 'insert') {
            $mySession = Yii::app()->user->getState('pluploaded_file');
            $ext = MyHelpers::getInstance()->getExtString($mySession['file_name']);
            $uid = uniqid();
            $this->file  = $uid . '.' . $ext;
            $this->thumb = $uid . '_thumb.' . $ext;
        }
    }
    
    protected function afterSave() {
        $mySession   = Yii::app()->user->getState($this->params['plupload_session']);
        
        //move file
        $tempDir = Yii::app()->params['tempo_dir'];
        $slideshowDir = Yii::app()->params['upload_dir'] . $this->params['basename'] . '/';
        
        rename($tempDir . $mySession['file_name'],
            $slideshowDir . $this->file
        );
        rename($tempDir . $mySession['thumb_name'],
            $slideshowDir . $this->thumb
        );
        
        //clear session
        Yii::app()->user->setState($this->params['plupload_session'], null);
    }
 
    /**
     * @param integer $id
     * @return boolean
     */
    public function find($id) {
        $content = $this->getContent();
        if (isset($content[$id])) {
            foreach($content[$id] as $key => $value) {
                $this->$key = $value;
            }
            $this->id = $id;
            $this->restoreSession();
            
            return TRUE;
        } else {
            return FALSE;
        }
    }
    
    private function restoreSession() {
        if (! Yii::app()->user->hasState($this->params['plupload_session'])) {
            //move file
            $tempDir = Yii::app()->params['tempo_dir'];
            $slideshowDir = Yii::app()->params['upload_dir'] . $this->params['basename'] . '/';

            copy($slideshowDir . $this->file,
                $tempDir . $this->file
            );
            copy($slideshowDir . $this->thumb,
                $tempDir . $this->thumb
            );

            //write session
            Yii::app()->user->setState($this->params['plupload_session'], array(
                'file_name'  => $this->file,
                'thumb_name' => $this->thumb,
            ));
        }
    }
    
    public function clearSession() {
        $session = Yii::app()->user->getState($this->params['plupload_session']);
        $tempoDir = Yii::app()->params['tempo_dir'];
        if (is_file($tempoDir . $session['file_name']))
            unlink($tempoDir . $session['file_name']);
        if (is_file($tempoDir . $session['thumb_name']))
            unlink($tempoDir . $session['thumb_name']);
        Yii::app()->user->setState($this->params['plupload_session'], null);
    }
}